package com.knightcloud.micro.auth.config.oauth2;

import lombok.RequiredArgsConstructor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2TokenIntrospectionAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 不透明令牌(OpaqueToken)内省
 *
 * @author knight
 * @see org.springframework.security.oauth2.server.authorization.authentication.OAuth2TokenIntrospectionAuthenticationProvider;
 */
@Component
@RequiredArgsConstructor
public class CustomOpaqueTokenIntrospector implements OpaqueTokenIntrospector {

	private static final String AUTHORITY_PREFIX = "SCOPE_";

	private static final TypeDescriptor OBJECT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);

	private static final TypeDescriptor LIST_STRING_TYPE_DESCRIPTOR = TypeDescriptor.collection(List.class,
			TypeDescriptor.valueOf(String.class));

	private final OAuth2AuthorizationService authorizationService;

	/**
	 * authorizedToken -> claims
	 * @param authorizedToken 授权令牌
	 * @see OAuth2TokenIntrospectionAuthenticationProvider #withActiveTokenClaims()
	 * @return {@link Map}<{@link String}, {@link Object}>
	 */
	private static Map<String, Object> withActiveTokenClaims(OAuth2Authorization.Token<OAuth2Token> authorizedToken) {
		Map<String, Object> result = new HashMap<>();

		if (!CollectionUtils.isEmpty(authorizedToken.getClaims())) {
			result.putAll(convertClaimsIfNecessary(authorizedToken.getClaims()));
		}

		OAuth2Token token = authorizedToken.getToken();
		if (token.getIssuedAt() != null) {
			result.put(OAuth2TokenIntrospectionClaimNames.IAT, token.getIssuedAt());
		}
		if (token.getExpiresAt() != null) {
			result.put(OAuth2TokenIntrospectionClaimNames.EXP, token.getExpiresAt());
		}

		if (OAuth2AccessToken.class.isAssignableFrom(token.getClass())) {
			OAuth2AccessToken accessToken = (OAuth2AccessToken) token;
			result.put(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE, accessToken.getTokenType().getValue());
		}
		return result;
	}

	/**
	 * 声称如果有必要转换
	 * @param claims 索赔
	 * @see OAuth2TokenIntrospectionAuthenticationProvider #convertClaimsIfNecessary()
	 * @return {@link Map}<{@link String}, {@link Object}>
	 */
	private static Map<String, Object> convertClaimsIfNecessary(Map<String, Object> claims) {
		Map<String, Object> convertedClaims = new HashMap<>(claims);

		Object value = claims.get(OAuth2TokenIntrospectionClaimNames.ISS);
		if (value != null && !(value instanceof URL)) {
			URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class);
			if (convertedValue != null) {
				convertedClaims.put(OAuth2TokenIntrospectionClaimNames.ISS, convertedValue);
			}
		}

		value = claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE);
		if (value != null && !(value instanceof List)) {
			Object convertedValue = ClaimConversionService.getSharedInstance()
				.convert(value, OBJECT_TYPE_DESCRIPTOR, LIST_STRING_TYPE_DESCRIPTOR);
			if (convertedValue != null) {
				convertedClaims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, convertedValue);
			}
		}

		value = claims.get(OAuth2TokenIntrospectionClaimNames.AUD);
		if (value != null && !(value instanceof List)) {
			Object convertedValue = ClaimConversionService.getSharedInstance()
				.convert(value, OBJECT_TYPE_DESCRIPTOR, LIST_STRING_TYPE_DESCRIPTOR);
			if (convertedValue != null) {
				convertedClaims.put(OAuth2TokenIntrospectionClaimNames.AUD, convertedValue);
			}
		}

		return convertedClaims;
	}

	@Override
	public OAuth2AuthenticatedPrincipal introspect(String token) {
		OAuth2Authorization authorization = this.authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
		if (authorization == null) {
			throw new BadOpaqueTokenException("Provided token isn't active");
		}

		OAuth2Authorization.Token<OAuth2Token> authorizedToken = authorization.getToken(token);
		if (authorizedToken == null || !authorizedToken.isActive()) {
			throw new BadOpaqueTokenException("Provided token isn't active");
		}

		Map<String, Object> claims = withActiveTokenClaims(authorizedToken);

		return convertClaimsSet(claims);
	}

	private OAuth2AuthenticatedPrincipal convertClaimsSet(Map<String, Object> claims) {
		claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.AUD, (k, v) -> {
			if (v instanceof String) {
				return Collections.singletonList(v);
			}
			return v;
		});
		claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, (k, v) -> v.toString());
		claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.ISS, (k, v) -> v.toString());
		Collection<GrantedAuthority> authorities = new ArrayList<>();
		claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.SCOPE, (k, v) -> {
			if (v instanceof String) {
				Collection<String> scopes = Arrays.asList(((String) v).split(" "));
				for (String scope : scopes) {
					authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope));
				}
				return scopes;
			}
			return v;
		});
		claims.computeIfPresent("authorities", (k, v) -> {
			if (v instanceof List authoritiesClaim) {
				for (Object authority : authoritiesClaim) {
					authorities.add(new SimpleGrantedAuthority(authority.toString()));
				}
			}
			return v;
		});
		return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities);
	}

}
